import time
import threading
from config import Config
from modbus.serial_manager import SerialManager
from modbus.rtu_protocol import ModbusRTUProtocol
from modbus.data_processor import DataProcessor
from gui.main_window import MainWindow
import logging


class ModbusController:
    """Modbus主控制器"""

    def __init__(self):
        # 初始化配置
        self.config = Config()

        # 初始化串口管理
        self.serial_manager = SerialManager(self.config)

        # 初始化Modbus协议
        self.modbus_protocol = ModbusRTUProtocol(self.serial_manager, self.config)

        # 初始化数据处理
        self.data_processor = DataProcessor(self.modbus_protocol, self.config)

        # 初始化轮询线程
        self.polling_thread = None
        self.polling_active = False

        # 初始化GUI
        self.gui = MainWindow(self, self.config)
        self.gui.update_ui()

    def get_available_ports(self):
        """获取可用串口列表"""
        return self.serial_manager.get_available_ports()

    def connect(self, port):
        """连接串口"""
        if self.serial_manager.connect(port):
            return True
        return False

    def disconnect(self):
        """断开串口连接"""
        self.stop_polling()
        self.serial_manager.disconnect()

    def is_connected(self):
        """检查是否已连接"""
        return self.serial_manager.connected

    def start_polling(self):
        """开始轮询寄存器"""
        if not self.is_connected():
            return False

        if not self.polling_active:
            self.polling_active = True
            self.polling_thread = threading.Thread(
                target=self._polling_loop,
                daemon=True
            )
            self.polling_thread.start()
            return True
        return False

    def stop_polling(self):
        """停止轮询寄存器"""
        self.polling_active = False
        if self.polling_thread and self.polling_thread.is_alive():
            self.polling_thread.join(timeout=1.0)

    def is_polling(self):
        """检查是否正在轮询"""
        return self.polling_active

    def _polling_loop(self):
        """轮询循环"""
        logging.info("轮询开始")

        while self.polling_active and self.is_connected():
            try:
                # 轮询寄存器
                self.data_processor.poll_registers()

                # 按配置间隔等待
                poll_interval = self.config.get_modbus_config().get("poll_interval", 1.0)
                time.sleep(poll_interval)
            except Exception as e:
                logging.error(f"轮询错误: {str(e)}")
                time.sleep(1)

        logging.info("轮询停止")

    def read_registers(self, start_address, count):
        """读取寄存器"""
        if not self.is_connected():
            return

        values = self.modbus_protocol.read_holding_registers(start_address, count)
        if values:
            logging.info(f"读取成功: 地址 0x{start_address:04X}, 值: {values}")
        else:
            logging.error(f"读取失败: 地址 0x{start_address:04X}")

    def write_register(self, address, value):
        """写入寄存器"""
        if not self.is_connected():
            return

        if self.modbus_protocol.write_single_register(address, value):
            logging.info(f"写入成功: 地址 0x{address:04X}, 值: {value}")
        else:
            logging.error(f"写入失败: 地址 0x{address:04X}, 值: {value}")

    def get_registers(self):
        """获取所有寄存器"""
        return self.data_processor.get_all_registers()

    def get_register(self, address):
        """获取指定寄存器"""
        return self.data_processor.get_register(address)

    def get_history(self, address):
        """获取寄存器历史数据"""
        return self.data_processor.data_history.get(address, [])

    def set_device_address(self, address):
        """设置设备地址"""
        self.modbus_protocol.device_address = address
        self.config.update_modbus_config("device_address", address)
        self.config.save_config()

    def shutdown(self):
        """关闭系统"""
        self.stop_polling()
        self.disconnect()
        self.config.save_config()


if __name__ == "__main__":
    # 创建控制器
    controller = ModbusController()

    # 启动主循环
    controller.gui.mainloop()
